#ifndef LHC_UTILITIES_TEMPLATES_H_INCLUDED_
#define LHC_UTILITIES_TEMPLATES_H_INCLUDED_

#include "Endian.h"
#include "utilities.h"
#include <vector>

// Template implementation

namespace lhcutils
{

template<typename T>
T GetFromBytes(const uint8_t* bytes, Endianness::Value endianness)
{
	if(endianness == GetHostEndianness())
	{
		T ret = *(reinterpret_cast<const T*>(bytes));
		return ret;
	}
	else
	{
		std::vector<uint8_t> reversedBytes(sizeof(T));
		for(size_t reverseByteNum = 0; reverseByteNum < sizeof(T); reverseByteNum++)
		{
			reversedBytes.push_back(bytes[sizeof(T) - 1 - reverseByteNum]);
		}
		
		T ret = *(reinterpret_cast<const T*>(&(reversedBytes[0])));
		return ret;
	}
}

template<typename T>
void AppendBytes(std::vector<uint8_t>& vec, T data, Endianness::Value endianness)
{
	Endianness::Value hostEndianness = GetEndianness();
	if(hostEndianness == endianness)
	{
		uint8_t* dataBegin = reinterpret_cast<uint8_t*>(&data);
		for(int byteIndex = 0; byteIndex < sizeof(T); byteIndex++)
		{
			vec.push_back(dataBegin[byteIndex]);
		}
	}
	else
	{
		uint8_t dataBegin = reinterpret_cast<uint8_t*>(&data);
		for(int byteIndex = sizeof(T) - 1; byteIndex >= 0; byteIndex--)
		{
			vec.push_back(dataBegin[byteIndex]);
		}
	}
}

template<typename T>
bool GetBit(T number, unsigned int bitIndex)
{
	return (number & (1 << bitIndex)) != 0;
}


}

#endif

/*
 Copyright 2011 Greg Najda

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
